import tkinter as tk

class BallGame:
    def __init__(self, root):
        self.root = root
        self.root.title("Ball Game")
        self.canvas = tk.Canvas(root, width=550, height=550, bg="white")
        self.canvas.pack()

        # 网格大小
        self.grid_size = 50
        self.grid_width = 11
        self.grid_height = 11

        # 初始位置
        self.ball_x = 5
        self.ball_y = 10

        # 绘制网格
        self.draw_grid()

        # 绘制球
        self.ball = self.canvas.create_oval(
            self.ball_x * self.grid_size + 5,
            self.ball_y * self.grid_size + 5,
            (self.ball_x + 1) * self.grid_size - 5,
            (self.ball_y + 1) * self.grid_size - 5,
            fill="red"
        )

        # 绑定按键事件
        self.root.bind("<KeyPress-1>", self.move_left)
        self.root.bind("<KeyPress-2>", self.move_right)

    def draw_grid(self):
        for i in range(self.grid_width + 1):
            self.canvas.create_line(i * self.grid_size, 0, i * self.grid_size, self.grid_height * self.grid_size, fill="gray")
        for j in range(self.grid_height + 1):
            self.canvas.create_line(0, j * self.grid_size, self.grid_width * self.grid_size, j * self.grid_size, fill="gray")

    def start(self, live_man):
        live_man.set_ball_game(self)  # 设置BallGame实例到DouyinLiveWebFetcher
        self.root.mainloop()

    def move_left(self, event):
        if self.ball_x > 0:
            self.ball_x -= 1
            self.canvas.coords(self.ball,
                               self.ball_x * self.grid_size + 5,
                               self.ball_y * self.grid_size + 5,
                               (self.ball_x + 1) * self.grid_size - 5,
                               (self.ball_y + 1) * self.grid_size - 5)

    def move_right(self, event):
        if self.ball_x < self.grid_width - 1:
            self.ball_x += 1
            self.canvas.coords(self.ball,
                               self.ball_x * self.grid_size + 5,
                               self.ball_y * self.grid_size + 5,
                               (self.ball_x + 1) * self.grid_size - 5,
                               (self.ball_y + 1) * self.grid_size - 5)